﻿using System.Text.Json.Serialization;

namespace ZGDisassembler.Core;
internal class Utils
{

	#region 将数组拼合成16进制数
	/// <summary>
	/// 将数组拼合成16进制数
	/// </summary>
	/// <param name="data"></param>
	/// <returns></returns>
	internal static uint? CombineHex(Span<byte> data, bool lowToHigh = true)
	{
		if (data.IsEmpty)
			return null;

		uint result = 0;
		if (lowToHigh)
		{
			byte offset = 0;
			for (var i = 0; i < data.Length; ++i)
			{
				result |= (uint)(data[i] << offset);
				offset += 8;
			}
		}
		else
		{
			for (var i = data.Length - 1; i >= 0; i--)
			{
				result <<= 8;
				result |= data[i];
			}
		}
		return result;
	}
	#endregion 将数组拼合成16进制数

	internal static uint? CheckNumber(string text)
	{
		text = text.Trim();
		var match = Regex.Match(text.Trim(), "(?<hex>^0[xX][0-9a-fA-F]+)|(?<dec>^[0-9]+)");
		if (!match.Success)
			return null;

		if (match.Groups["hex"].Success)
			return Convert.ToUInt32(text, 16);
		else
			return Convert.ToUInt32(text);
	}
}

public class JsonHexConverter : JsonConverter<uint?>
{
	public override uint? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
	{
		if (reader.TokenType == JsonTokenType.String)
		{
			var value = Utils.CheckNumber(reader.GetString());
			return value;
		}

		if (reader.TokenType == JsonTokenType.Number)
			return reader.GetUInt32();

		return null;
	}

	public override void Write(Utf8JsonWriter writer, uint? value, JsonSerializerOptions options)
	{
		if (value == null)
			writer.WriteNullValue();

		writer.WriteNumberValue((uint)value);
	}
}

